package cn.hdu.liang.nio;

import java.io.IOException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class SelectorTest {
    public static void main(String[] args) {
        try(Selector selector = Selector.open();
            SelectableChannel channel = SocketChannel.open()) {
            channel.configureBlocking(false);
            channel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ);

            int n = 10;
            while(n-- > 0) {
                int readyChannels = selector.select();
                if(readyChannels == 0) {
                    continue;
                }

                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
                while(keyIterator.hasNext()) {
                    SelectionKey key = keyIterator.next();
                    if(key.isAcceptable()) {
                        System.out.println("a connection was accepted by a ServerSocketChannel.");
                    } else if(key.isConnectable()) {
                        System.out.println("a connection was established with a remote server.");
                    } else if(key.isReadable()) {
                        System.out.println("a channel is ready for reading");
                    } else if(key.isWritable()) {
                        System.out.println("a channel is ready for writing");
                    }
                    keyIterator.remove();
                }

            }
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}